package com.lingshu.app.base;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;

import com.lingshu.app.R;
import com.lingshu.app.config.LoadState;
import com.lingshu.app.databinding.FragmentBaseBinding;
import com.lingshu.app.databinding.ViewLoadErrorBinding;
import com.lingshu.app.databinding.ViewLoadingBinding;
import com.lingshu.app.databinding.ViewNoDataBinding;
import com.lingshu.app.databinding.ViewNoNetworkBinding;
import com.lingshu.app.ui.login.LoginActivity;

import cn.hutool.core.util.StrUtil;

/**
 * @author 于定金
 * @version 1.0
 * @Date 2023/12/28 16:55
 * @Description
 */
public abstract class BaseFragment<DB extends ViewDataBinding, VM extends BaseViewModel> extends Fragment {
    protected boolean isDialogShown = false; // 标志位

    protected DB dataBinding;
    protected VM viewModel;
    protected AppCompatActivity context;

    private AlertDialog globalDialog;
    private FragmentBaseBinding fragmentBaseBinding;
    private ViewLoadingBinding viewLoadingBinding;
    private ViewLoadErrorBinding viewLoadErrorBinding;
    private ViewNoDataBinding viewNoDataBinding;
    private ViewNoNetworkBinding viewNoNetworkBinding;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        if (args != null) {
            handleArguments(args);
        }
        initViewModel();

        // ViewModel订阅生命周期事件
        if (viewModel != null) {
            getLifecycle().addObserver(viewModel);
        }
        //统一的提示信息
        viewModel.infoMsg.observe(context, msg -> {
            showMessage(msg);
        });
        //统一的跳转
        viewModel.tokenIsValid.observe(context, result -> {
            if (!result) {
                Intent intent = new Intent(context, LoginActivity.class);
                startActivity(intent);
            }
        });
    }

    /**
     * 弹出信息
     *
     * @param message
     */
    public void showMessage(String message) {
        if (StrUtil.isNotBlank(message)) {
            if (!isDialogShown) {
                isDialogShown = true;
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                View dialogView = getLayoutInflater().inflate(R.layout.custom_message_dialog, null);
                TextView textView = dialogView.findViewById(R.id.tv_global);
                textView.setText(message);
                dialogView.findViewById(R.id.img_global_close).setOnClickListener(v -> globalDialog.dismiss());
                builder.setView(dialogView);
                globalDialog = builder.create();
                globalDialog.setOnDismissListener(dialog -> {
                    isDialogShown = false;
                    viewModel.infoMsg.postValue(null);
                });
                globalDialog.setOnCancelListener(dialog -> {
                    isDialogShown = false;
                    viewModel.infoMsg.postValue(null);
                });
                globalDialog.show();
            }
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        fragmentBaseBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_base, container, false);
        dataBinding = DataBindingUtil.inflate(inflater, getLayoutResId(), fragmentBaseBinding.flContentContainer, true);
        bindViewModel();
        dataBinding.setLifecycleOwner(this);
        initLoadState();
        init();
        return fragmentBaseBinding.getRoot();
    }

    private void initLoadState() {
        viewModel.loadState.observe(getViewLifecycleOwner(), loadState -> {
            switchLoadView(loadState);
        });
    }

    /**
     * 根据加载状态 ， 切换不同的View
     *
     * @param loadState
     */
    private void switchLoadView(LoadState loadState) {
        removeLoadView();

        switch (loadState) {
            case LOADING:
                if (viewLoadingBinding == null) {
                    viewLoadingBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.view_loading, fragmentBaseBinding.flContentContainer, false);
                }
                fragmentBaseBinding.flContentContainer.addView(viewLoadingBinding.getRoot());
                break;

            case NO_NETWORK:
                if (viewNoNetworkBinding == null) {
                    viewNoNetworkBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.view_no_network, fragmentBaseBinding.flContentContainer, false);
                    viewNoNetworkBinding.setViewModel(viewModel);
                }
                fragmentBaseBinding.flContentContainer.addView(viewNoNetworkBinding.getRoot());
                break;

            case NO_DATA:
                if (viewNoDataBinding == null) {
                    viewNoDataBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.view_no_data, fragmentBaseBinding.flContentContainer, false);
                }
                fragmentBaseBinding.flContentContainer.addView(viewNoDataBinding.getRoot());
                break;

            case ERROR:
                if (viewLoadErrorBinding == null) {
                    viewLoadErrorBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.view_load_error, fragmentBaseBinding.flContentContainer, false);
                    viewLoadErrorBinding.setViewModel(viewModel);
                }
                fragmentBaseBinding.flContentContainer.addView(viewLoadErrorBinding.getRoot());
                break;

            default:
                break;
        }
    }

    /**
     * 移除view
     */
    private void removeLoadView() {
        int childCount = fragmentBaseBinding.flContentContainer.getChildCount();
        if (childCount > 1) {
            fragmentBaseBinding.flContentContainer.removeViews(1, childCount - 1);
        }
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        if (context instanceof AppCompatActivity) {
            this.context = (AppCompatActivity) context;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (viewModel != null) {
            getLifecycle().removeObserver(viewModel);
        }
        removeLoadView();
    }

    /**
     * 处理参数
     *
     * @param args 参数容器
     */
    protected void handleArguments(Bundle args) {

    }

    /**
     * 是否支持页面加载。默认不支持
     *
     * @return true表示支持，false表示不支持
     */
    protected boolean isSupportLoad() {
        return false;
    }

    /**
     * 获取当前页面的布局资源ID
     *
     * @return 布局资源ID
     */
    protected abstract int getLayoutResId();

    /**
     * 初始化ViewModel
     */
    protected abstract void initViewModel();

    /**
     * 绑定ViewModel
     */
    protected abstract void bindViewModel();

    /**
     * 初始化
     */
    protected abstract void init();
}
